﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Blog.Core.Data;
using Blog.Core.Model.Model;
using Blog.Core.Model.ViewModel;

namespace Blog.Core.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserRolesController : ControllerBase
    {
        private readonly BlogContext _context;

        public UserRolesController(BlogContext context)
        {
            _context = context;
        }
        [HttpGet]
        public async Task<IActionResult> GetPagiUsersAsync(string query, int pageIndex, int pageSize = 5)
        {
            var users = _context.UserRoles.Include(c => c.User).Include(c => c.Role).Where(c => c.Role.Name != "admin").AsNoTracking();

            if (!string.IsNullOrEmpty(query))
            {
                users = users.Where(c => c.User.UserName.Contains(query));
            }
            var userTDOes = users.Select(s => new UserDTO(s.User, s.Role));
            var total = await userTDOes.CountAsync();

            var userList = await PaginatedList<UserDTO>.CreateAsync(userTDOes, pageIndex, pageSize, total);
            return Ok(new { total, userList });
        }

        [HttpGet("{username}")]
        public async Task<ActionResult<User>> GetUserAsync(string username){
            return await _context.Users.FindAsync(username);
        }
        [HttpPost]
        public async Task<ActionResult<User>> PostUsersAsync(UserRoleDTO userRoleDTO)
        {
            if (userRoleDTO is null)
            {
                throw new ArgumentNullException(nameof(userRoleDTO));
            }
            if (UserExists(username: userRoleDTO.UserName))
            {
                return Conflict();
            }
            var role = await _context.Roles.FindAsync("default");
            var userRole = new UserRole { User = new User { UserName = userRoleDTO.UserName, Password = userRoleDTO.Password }, Role = role };
            _context.UserRoles.Add(userRole);
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                throw;
            }
            return await GetUserAsync(userRoleDTO.UserName);
        }

        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteUserRole(string id)
        {
            var user = await _context.Users.FindAsync(id);
            if (user == null)
            {
                return NotFound();
            }

            _context.Users.Remove(user);

            
            var userRole = await _context.UserRoles.Where(c => c.UserID == user.UserName).ToListAsync();
            if (userRole.Count != 0)
            {
                _context.UserRoles.RemoveRange(userRole);
            }
            await _context.SaveChangesAsync();
            return NoContent();
        }

        [HttpOptions]
        public IActionResult AddUserRole()
        {
            return Ok();
        }

        private bool UserRoleExists(string id)
        {
            return _context.UserRoles.Any(e => e.RoleID == id);
        }
        private bool UserExists(string username)
        {
            return _context.Users.Any(e => e.UserName == username);
        }
    }
}
